package main

import (
	"fmt"
	"context"
)

func main() {
	newRandStream := func(ctx context.Context) <-chan int {
		randStream := make(chan int)
		n := 1
		go func() {
			defer fmt.Println("newRandStream closure exited.")
			defer close(randStream)

			for {
				select {
				case <-ctx.Done():
					return
				case randStream <- n:
					n++
				}
			}

		}()

		return randStream
	}

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()


	for n := range newRandStream(ctx) {
		fmt.Println(n)
		if n == 5 {
			break
		}
	}


}